//
//  CartViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/6/21.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "CartViewController.h"

#import "CartFooterView.h"//页脚View
#import "CartTableViewCell.h"//cell
#import "CartEditTableViewCell.h"//编辑Cell

#import "CartModel.h"//商品Model

#import "GoodsDetailViewController.h"//商品详情页Controller
#import "CommitOrderViewController.h"//提交订单Controller

@interface CartViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation CartViewController
{
    NSUserDefaults *_defaults;//沙盒
    CartFooterView *_footerView;
    
    NSMutableArray *_cartArray;

    NSMutableArray *_cellSelectedButtonArray;//cell选择按钮数组
    
    BOOL _isSelectedAll;//全选状态
    BOOL _isEditing;    //全编辑状态
    
    NSMutableArray *_editNumArray;//编辑数量暂存数组
}

 static NSString *const CartFooterViewID = @"CartFooterView";
 static NSString *const CartTableViewCellID = @"CartTableViewCell";
 static NSString *const CartEditTableViewCellID = @"CartEditTableViewCell";

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self getCartPage];
    [self AllGoods];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isSelectedAll = NO;
    _isEditing = NO;
    _defaults = [NSUserDefaults standardUserDefaults];
    _cellSelectedButtonArray = [NSMutableArray array];
    
    //设置导航栏
    [self setNav];
    
    //设置tableView
    [self setTableView];
    
    //设置页脚
    [self setFooterView];
    
}


#pragma mark === 设置导航栏 ===
- (void)setNav{
    self.title = @"购物车";
    
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(edit:)];
    UIBarButtonItem *rightItem2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"moreicon"] style:UIBarButtonItemStylePlain target:self action:@selector(more)];
    self.navigationItem.rightBarButtonItems = @[rightItem2, rightItem1];
}


#pragma mark === 注册TableView ===
- (void)setTableView{
    //注册自定义cell
    [self.tableView registerNib:[UINib nibWithNibName:@"CartTableViewCell" bundle:nil] forCellReuseIdentifier:CartTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CartEditTableViewCell" bundle:nil] forCellReuseIdentifier:CartEditTableViewCellID];
}

#pragma mark === 设置结算合计 页脚 ===
- (void)setFooterView{
    _footerView = [[CartFooterView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 105, SCREEN_WIDTH, 55)];
    [_footerView.chooseBtn addTarget:self action:@selector(chooseAll) forControlEvents:UIControlEventTouchUpInside];
    [_footerView.settlement addTarget:self action:@selector(settlement:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_footerView];
}



#pragma mark === TableViewDelegate ===
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_cartArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CartModel *model = _cartArray[indexPath.row];
    
    //非编辑状态
    if (!_isEditing) {
        CartTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CartTableViewCellID];
        cell.price.text = model.price;
        cell.cellClick = ^(){
            model.isSelected = !model.isSelected;
            
            //判断商品全选
            [self AllGoods];
    
            //刷新分段
            [_tableView reloadData];
            
            //合计
            [self total];
        };
        
        //cell被选
        if (model.isSelected) {
            cell.chooseImage.image = [UIImage imageNamed:@"GLDZicon_08"];
            cell.chooseImage.backgroundColor = APPCOLOR;
        //cell未被选
        }else{
            cell.chooseImage.image = [UIImage imageNamed:@"GLDZicon_13"];
            cell.chooseImage.backgroundColor = [UIColor clearColor];
        }
        
    
        [_cellSelectedButtonArray replaceObjectAtIndex:indexPath.row withObject:cell.chooseButton];

        
        cell.goodsName.text = model.goodsName;
        cell.goodsDetail.text = model.goodsDetail;
        cell.colorAndSize.text = model.colorAndSize;
        cell.price.text = [NSString stringWithFormat:@"¥%@", model.price];
        cell.num.text = model.num;
        [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:model.IMGURL]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    
    }
    //编辑状态
    else{
        CartEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CartEditTableViewCellID];
        cell.colorAndSize.text = model.colorAndSize;
        cell.num.text = model.num;
        cell.num.delegate = cell;
        cell.editNum = ^(NSString *num){
            [self changeCartNum:num andIndex:indexPath.row];
        };
        
        //selected
        cell.cellClick = ^(){
            model.isSelected = !model.isSelected;
            
            //判断商品全选
            [self AllGoods];
            
            //刷新分段
            [_tableView reloadData];
            
            //合计
            [self total];
        };
        
        //cell被选
        if (model.isSelected) {
            cell.chooseImage.image = [UIImage imageNamed:@"GLDZicon_08"];
            cell.chooseImage.backgroundColor = APPCOLOR;
        //cell未被选
        }else{
            cell.chooseImage.image = [UIImage imageNamed:@"GLDZicon_13"];
            cell.chooseImage.backgroundColor = [UIColor clearColor];
        }
        
        //选择按钮加入按钮数组
        [_cellSelectedButtonArray replaceObjectAtIndex:indexPath.row withObject:cell.chooseButton];
        
        
        [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:model.IMGURL]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
//商品选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CartModel *model = _cartArray[indexPath.row];
    
    GoodsDetailViewController *goodsDetail = [[GoodsDetailViewController alloc] init];
    goodsDetail.hidesBottomBarWhenPushed = YES;
    
    goodsDetail.modelId = model.Id;
    goodsDetail.modelProductCode = model.ProductCode;
    [self.navigationController pushViewController:goodsDetail animated:YES];
}


//TableViewDelegate编辑方法
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self deleteCart:indexPath.row];
        [_cartArray removeObjectAtIndex:indexPath.row];
        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [self total];
    }
}

#pragma mark === 全选结算 页脚点击事件 ===
//全选
- (void)chooseAll{
    _isSelectedAll = !_isSelectedAll;
    //1 全选
    if (_isSelectedAll) {
        _footerView.chooseImage.image = [UIImage imageNamed:@"GLDZicon_08"];
        _footerView.chooseImage.backgroundColor = APPCOLOR;
        //所有商品全选
        for (int j = 0; j < [_cartArray count]; j++) {
            CartModel *model = _cartArray[j];
            model.isSelected = YES;
        }
        
    //2 取消全选
    }else{
        _footerView.chooseImage.image = [UIImage imageNamed:@"GLDZicon_13"];
        _footerView.chooseImage.backgroundColor = [UIColor clearColor];
        
        //所有商品取消全选
        for (int j = 0; j < [_cartArray count]; j++) {
            CartModel *model = _cartArray[j];
            model.isSelected = NO;
        }
    }
    //刷新TableView
    [_tableView reloadData];
    
    //合计
    [self total];
    
}
//判断所有商品是否全选
- (void)AllGoods{
    //1 判断商品全选
    int flag = 0;
    for (int i = 0; i < [_cartArray count]; i++) {
        CartModel *model = _cartArray[i];
        if (model.isSelected == NO) {
            flag++;
        }
    }
    
    if (_cartArray.count == 0) {
        flag = -1;
    }
    
    //所有全选
    if (flag == 0) {
        _isSelectedAll = YES;
        _footerView.chooseImage.image = [UIImage imageNamed:@"GLDZicon_08"];
        _footerView.chooseImage.backgroundColor = APPCOLOR;
    //所有未全选
    }else{
        _isSelectedAll = NO;
        _footerView.chooseImage.image = [UIImage imageNamed:@"GLDZicon_13"];
        _footerView.chooseImage.backgroundColor = [UIColor clearColor];
    }
}

#pragma MARK === 合计 ===
- (void)total{
    float totalMoney = 0;
    for (CartModel *model in _cartArray) {
        if (model.isSelected) {
            totalMoney += [model.price floatValue] * [model.num intValue];
        }
    }
    _footerView.total.text = [NSString stringWithFormat:@"合计: ¥%.2f",totalMoney];
}
//结算
- (void)settlement:(UIButton *)sender{
    NSLog(@"结算");
    
    if (![_defaults objectForKey:@"UserName"]){
        [EBUtility prompt:@"请登录" with:self];
        return;
    }
    
    //全选
    if (_isSelectedAll) {
        CommitOrderViewController *commit = [[CommitOrderViewController alloc] init];
        commit.packageArray = _cartArray;
        commit.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:commit animated:YES];
        
    //未全选
    }else{
        NSMutableArray *buyArray = [NSMutableArray array];
        for (CartModel *model in _cartArray) {
            if (model.isSelected == YES) {
                [buyArray addObject:model];
            }
        }
        
        //没有选择商品
        if (buyArray.count == 0) {
            [EBUtility prompt:@"请选择商品" with:self];
        //选择的商品进行订单提交
        }else{
            CommitOrderViewController *commit = [[CommitOrderViewController alloc] init];
            commit.packageArray = buyArray;
            commit.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commit animated:YES];
        }
    }
}



#pragma mark === 导航栏Item点击事件 ===
//编辑
- (void)edit:(UIBarButtonItem *)item{
    _isEditing = !_isEditing;
    if (_isEditing) {
        [item setTitle:@"完成"];
    }else{
        [item setTitle:@"编辑"];
        [self requestCartList];
        [self chooseAll];
    }
    [_tableView reloadData];
}
//更多
- (void)more{
    NSLog(@"更多");
}

#pragma mark === 网络请求 ===
//购物车页数
- (void)getCartPage{
    if (![_defaults objectForKey:@"UserName"]) {
        [EBUtility prompt:@"请登录" with:self];
        return;
    }
    
    //总页数
    NSDictionary *paramentss = @{
                                 @"userName"   : [_defaults objectForKey:@"UserName"],
                                 @"cKeys"      : @""
                                 };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetShopCartPageCount?" withParaments:paramentss withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            NSLog(@"总页数%@", object[@"TotalCount"]);
            [self requestCartList];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"购物车页数请求失败 : %@", error);
    } progress:nil];
}
//购物车列表
- (void)requestCartList{
    //列表
    NSDictionary *paraments = @{
                                @"userName"   : [_defaults objectForKey:@"UserName"],
                                @"cKeys"      : @"",
                                @"pageIndex"  : @"1",
                                };
    
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetShopCartListByPage?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            if (!_cartArray) {
                _cartArray = [NSMutableArray array];
            }else{
                [_cartArray removeAllObjects];
                [_cellSelectedButtonArray removeAllObjects];
            }
            
            [_defaults setObject:[NSString stringWithFormat:@"%@", object[@"TotalCount"]] forKey:@"CartNum"];
            
            for (NSDictionary *dic in object[@"Rows"]) {
                CartModel *model = [CartModel parseUserWithDictionary:dic];
                model.isSelected = NO;
                [_cartArray addObject:model];
                
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [_cellSelectedButtonArray addObject:button];
            }
            [_tableView reloadData];
        }else if ([object[@"Code"] isEqualToString:@"777"]){
            [_cartArray removeAllObjects];
            [_tableView reloadData];
            [_defaults removeObjectForKey:@"CartNum"];
            [self AllGoods];
            [self total];
        }
        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"购物车列表请求失败 : %@", error);
    } progress:nil];
}

#pragma mark === 删除购物车 ===
- (void)deleteCart:(NSInteger)index{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    CartModel *model = _cartArray[index];
    NSDictionary *paraments = @{
                                @"userName"   : [defaults objectForKey:@"UserName"],
                                @"skuNO"      : model.SKU
                                };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/DelItem?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            [self getCartPage];
            _isSelectedAll = YES;
            [self chooseAll];
            [self total];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"删除购物车失败 : %@", error);
    } progress:nil];
}

#pragma mark === 修改购物车数量 ===
- (void)changeCartNum:(NSString *)num andIndex:(NSInteger)index{
    CartModel *model = _cartArray[index];
    NSDictionary *paraments = @{
                                @"userName"   : [_defaults objectForKey:@"UserName"],
                                @"cId"        : model.CartID,
                                @"inputCount" : num
                                };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/ChangeCartCount?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        if ([object[@"Code"] isEqualToString:@"0"]) {
//            [EBUtility prompt:@"lalala" with:self];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"购物车数量修改失败 : %@", error);
    } progress:nil];
}

#pragma mark === 结算 ===
- (void)submitOrder{
    
    NSDictionary *paraments = @{
                                @"userid"     : [_defaults objectForKey:@"Id"],
                                @"userName"   : [_defaults objectForKey:@"UserName"],
                                @"remark"     : @"Chrome50,Chrome,50.0",
                                @"storeCode"  : @"777777",
                                @"ip"         : @"127.0.0.1",
                                @"mac"        : @"40:8D:5C:D6:2B:7A",
                                @"browser"    : @"Chrome50,Chrome,50.0",
                                @"osVer"      : @"Windows 7,Microsoft Windows NT 6.1.7601 Service Pack 1"
                                };
    
    NSLog(@"%@", paraments);
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/SubmitOrder?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
        NSLog(@"%@", object[@"Message"]);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            [EBUtility prompt:object[@"Message"] with:self];
            [self getCartPage];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品搜索网络请求失败 : %@", error);
    } progress:nil];

}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT - 105)style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
@end
